<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./dist/qrcode.js"></script>
  <script src="./dist/html2canvas.js"></script>
  <script src="./dist/jspdf.js"></script>
  <script src="./dist/moment.js"></script>
  <title>社保记录</title>
  <style>
    @media print {

      /* 设置横向打印 */
      /* 设置纵向打印 */
      @page {
        size: portrait;
      }
    }

    @font-face {
      font-family: 'FangzhengHeiti';
      src: url('./dist/FangZhengHeiTiJianTi-1.ttf') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FangZhengFangSongJianTi';
      src: url('./dist/FangZhengFangSongJianTi-1.ttf') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FangZhengKaiTiJianTi';
      src: url('./dist/FangZhengKaiTiJianTi-1.ttf') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FZYouHJW509R';
      src: url('./dist/FZYouHJW509R.TTF') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FZYouHK_504L';
      src: url('./dist/FZYouHK_504L.TTF') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FZHuaSJSJW-L';
      src: url('./dist/FZHuaSJSJW-L.TTF') format('truetype');
      /* 其他字体格式 */
    }

    @font-face {
      font-family: 'FZYouHK_505LL';
      src: url('./dist/FZYouHK_505L.TTF') format('truetype');
      /* 其他字体格式 */
    }

    body {
      font-family: 'Microsoft YaHei', sans-serif;
      margin: 0 auto;
      padding: 0;
      background-color: #fff;
    }



    .box {
      position: relative;
      padding: 0px;
      background-color: #fff;
      width: 1024px;
      height: 1449px;
      background: url(./dist/sb_00.png) center / 100% no-repeat;
      margin: 0 auto;
      /* font-family: 'SimSun', sans-serif; */
    }

    .qr {
      position: absolute;
      left: 5.1%;
      top: 2%
    }

    .pos {
      position: absolute;
    }

    .tips-code {
      top: 5px;
      left: 57.8%;
      font-size: 14px;
      font-family: 'FZHuaSJSJW-L';
      color: '#000';
      font-weight: 600;
      /* text-shadow: #000; */
    }

    .user-name {
      top: 11%;
      left: 17%;
      width: 65px;
      text-align: center;
    }

    .user-gender {
      top: 11%;
      left: 344px;
      width: 68px;
      text-align: center;
    }

    .user-code {
      top: 11%;
      left: 500px;
      width: 154px;
      text-align: center;
    }

    .user-idcardnumber {
      top: 11%;
      left: 730px;
      width: 234px;
      text-align: center;
    }

    .Insured-status {
      top: 15.7%;
      left: 17%;
      width: 65px;
      text-align: center;
    }

    .payment-num {
      top: 15.7%;
      left: 344px;
      width: 68px;
      text-align: center;
    }

    .Insured-entity-up {
      top: 15.7%;
      left: 500px;
      width: 464px;
      text-align: center;
    }

    .time-enrollment {
      left: 15%;
      width: 191px;
    }

    .Insured-entity-btm {
      left: 344px;
      width: 156px;
    }

    .handling-agency {
      left: 500px;
      width: 234px;
    }

    .insurance-type {
      left: 730px;
      width: 234px;
    }

    .cosl2 {
      top: 22.3%;
      height: 70px;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
    }


    table {
      position: absolute;
      top: 34.1%;
      left: 3%;
      height: 54px;
    }

    th,
    td {
      padding: 0;
      text-align: center;
      height: 49.6px !important;
      font-size: 14px;
      font-family: 'FZYouHK_504L';
      color: black;
      font-weight: 600;
    }

    .print-time {
      bottom: 13.8%;
      right: 11%
    }

    #exportButton {
      margin: 10px;
      padding: 8px 16px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      position: absolute;
      top: 24px;
      right: 24px;
    }

    #exportButton:hover {
      background-color: #0056b3;
    }
  </style>
</head>

<body>
  <div class="box" id="content">
    <div class="qr" id="qrcode"></div>
    <div class="tips-code pos"></div>
    <div class="user-name pos"></div>
    <div class="user-gender pos"></div>
    <div class="user-code pos"></div>
    <div class="user-idcardnumber pos"></div>
    <div class="Insured-status pos"></div>
    <div class="payment-num pos "></div>
    <div class="Insured-entity-up pos"></div>
    <!-- 参保时间 -->
    <div class="time-enrollment pos cosl2"></div>
    <!-- 参保单位 -->
    <div class="Insured-entity-btm pos cosl2"></div>
    <!-- 经办机构 -->
    <div class="handling-agency pos cosl2"></div>
    <!-- 险种 -->
    <div class="insurance-type pos cosl2"></div>
    <table>
      <tbody id="bottom-tr">
        <!-- 可以添加更多行 -->
      </tbody>
      </tbody>
    </table>
    <span class="print-time pos"></span>
  </div>
  <!-- Export button -->
  <button id="exportButton">导出</button>
  <!-- Scripts -->
  <script>

  </script>
  <script>
    var queryString = window.location.search
    var urlParams = new URLSearchParams(queryString)
    var id = urlParams.get('id')
    function generateRandomCode(length) {
      const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      let code = ''

      for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charset.length)
        code += charset[randomIndex]
      }

      return code
    }
    const code_v = generateRandomCode(32)
    function formatNumber(num) {
      if (num % 1 === 0) {
        return num.toFixed(0) // 如果小数位为0，则取整
      } else {
        return num.toFixed(2) // 如果小数位大于0，则保留两位小数
      }
    }
    // 上面表格数据
    var info = {
      name: "白梅", // 姓名
      gender: "女", // 性别
      personalNumber: "53010314144420", // 个人编号
      idCardNumber: "530427199307280921", // 身份证号
      insuranceStatus: "正常参保", // 当前参保缴费状态
      paidMonths: "31", // 实际缴费月数
      currentInsuranceUnit: "云南北极光数码科技有限公司", // 现参保单位
      insurancePeriod: "2021年03月至一", // 参保时间起止日期
      insuranceUnit: "云南北极光数码科技有限公司", // 参保单位
      handlingAgency: "昆明市盘龙区社会保险局", // 经办机构
      insuranceType: "城镇职工基本养老保险",   // 险种
      tips_url: 'https://hrss.yn.gov.cn/zwfw/form/', // 顶部验证系统链接
      tips_code: '', // 验证号码
      lister: '云南人社服务网上大厅(单位服务)',// 制表人
      print_time: '2023年10月10日',// 打印时间

    }
    // 用于动态填充用户信息的函数
    function fillUserInfo() {
      document.querySelector('.tips-code').innerText = info.tips_code
      document.querySelector('.user-name').innerText = info.name
      document.querySelector('.user-gender').innerText = info.gender
      document.querySelector('.user-code').innerText = info.personalNumber
      document.querySelector('.user-idcardnumber').innerText = info.idCardNumber

      document.querySelector('.Insured-status').innerText = info.insuranceStatus
      document.querySelector('.payment-num').innerText = info.paidMonths
      document.querySelector('.Insured-entity-up').innerText = info.currentInsuranceUnit

      document.querySelector('.time-enrollment').innerText = info.insurancePeriod
      document.querySelector('.Insured-entity-btm').innerText = info.insuranceUnit
      document.querySelector('.handling-agency').innerText = info.handlingAgency
      document.querySelector('.insurance-type').innerText = info.insuranceType
      // 创建一个 Date 对象，表示当前时间
      const currentDate = new Date()
      // 获取年、月、日
      const year = currentDate.getFullYear()
      const month = String(currentDate.getMonth() + 1).padStart(2, '0') // 月份是从 0 开始的，因此要加 1
      const day = String(currentDate.getDate()).padStart(2, '0')
      // 构建格式化的日期字符串（例如：2023-11-13）
      const formattedDate = `${year}年${month}月${day}日`
      document.querySelector('.print-time').innerText = info.print_time || formattedDate
    }

    // 下面表格数据
    var paymentData = [
      { paymentYear: 2022, paymentMonth: 1, paymentBase: 5000, companyPayment: 1000, personalPayment: 500, paymentStatus: "正常", paymentYear2: 2022, paymentMonth2: 1, paymentBase2: 5000, companyPayment2: 1000, personalPayment2: 500, paymentStatus2: "正常" },
      // 添加更多数据
    ]
    // 用于动态填充缴费情况表格的函数
    function fillPaymentTable() {
      var paymentTable = document.querySelector('.box table')
      var paymentBody = document.querySelector('#bottom-tr')
      // 清空表格内容
      paymentBody.innerHTML = ''
      // 遍历数据，动态生成表格行
      paymentData.forEach(function (payment) {
        var row = document.createElement('tr')
        row.innerHTML = `
          <td style="width: 78px;">${payment.paymentYear}</td>
          <td  style="width: 76px;">${Number(payment.paymentMonth || 0) < 10 ? `0${payment.paymentMonth}` : payment.paymentMonth}</td>
          <td style="width: 74px;">${payment.paymentBase ? formatNumber(Number(payment.paymentBase)) : 0}</td>
          <td style="width: 76px;">${payment.companyPayment ? formatNumber(Number(payment.companyPayment)) : 0}</td>
          <td style="width: 76px;">${payment.personalPayment ? formatNumber(Number(payment.personalPayment)) : 0}</td>
          <td style="width: 75px;">${payment.paymentStatus}</td>
          <td style="width: 76px;">${payment.paymentYear2 || ''}</td>
          <td style="width: 75px;">${Number(payment.paymentMonth2 || 0) < 10 ? `0${payment.paymentMonth2}` : payment.paymentMonth2}</td>
          <td style="width: 75px;">${payment.paymentBase2 ? formatNumber(Number(payment.paymentBase2)) : 0}</td>
          <td style="width: 76px;">${payment.companyPayment2 ? formatNumber(Number(payment.companyPayment2)) : 0}</td>
          <td style="width: 75px;">${payment.personalPayment2 ? formatNumber(Number(payment.personalPayment2)) : 0}</td>
          <td style="width: 76px;">${payment.paymentStatus2 || ''}</td>
        `
        paymentBody.appendChild(row)
      })
      paymentTable.appendChild(paymentBody)
    }
    // 获取当前页面的 URL
    var currentURL = `http://sys.ynjov.com/socialres.html?id=${id}&code=${code_v}` // 二维码

    // 创建 QRCode 实例并将二维码添加到页面
    var qrcode = new QRCode(document.getElementById("qrcode"), {
      text: currentURL,
      width: 98,
      height: 98
    })
    // 页面加载时调用填充表格数据的函数
    // 页面加载时调用填充用户信息和表格数据的函数
    window.onload = function () {
      if (urlParams.get('isMobile')) {
        document.getElementById("exportButton").hidden = true
        document.getElementById("tips").hidden = true
      }
      fetch(`http://api.ynjov.com:8080/api/getInsuredPersonDetail/${id}?insuredPersonId=${id}`)
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.json()
        })
        .then(({ data, items }) => {
          console.log(data)
          info = data
          info.tips_code = code_v.toLocaleLowerCase()
          excMonth(items || [])
          fillUserInfo()

        })
        .catch(error => {
          console.error('Fetch error:', error)
        })
    }
    function excMonth(data) {
      let dt = data.map(item => {
        return { ...item, date: moment(item.paymentYear + '' + (Number(item.paymentMonth) < 10 ? `0${item.paymentMonth}` : item.paymentMonth) + '01').format('YYYYMMDD') }
      }).sort((a, b) => Number(a.date - b.date))
      const lencop = 24 - dt.length + 1
      if (dt.length < 24) {
        for (let i = 1; i < lencop; i++) {
          const date = moment(dt[0].date).add(-i, 'months').format('YYYYMMDD')
          dt.push({
            companyPayment: 0,
            date,
            paymentYear: moment(date).format('YYYY'),
            paymentMonth: moment(date).format('M'),
            paymentStatus: '',
            paymentBase: 0,
            personalPayment: 0,
          })
        }
      }
      if (dt.length > 24) {
        dt.splice(0, length - 24)
      }
      dt = dt.sort((a, b) => Number(a.date - b.date))
      // 按照年和月排序
      const sortedData = dt.sort((a, b) => {
        if (a.paymentYear === b.paymentYear) {
          return a.paymentMonth - b.paymentMonth
        }
        return a.paymentYear - b.paymentYear
      }).slice(-24)

      // 计算分组位置
      const midIndex = Math.ceil(sortedData.length / 2)

      // 分组
      let leftGroup, rightGroup
      if (sortedData.length % 2 === 0) {
        leftGroup = sortedData.slice(0, midIndex)
        rightGroup = sortedData.slice(midIndex)
      } else {
        leftGroup = sortedData.slice(0, midIndex + 1)
        rightGroup = sortedData.slice(midIndex + 1)
      }

      // 如果左边元素多于右边，则调整右边的分组
      if (leftGroup.length > rightGroup.length) {
        rightGroup.push(leftGroup.pop())
      }


      // 输出分组数据
      let arr = []
      leftGroup.forEach((item, index) => {
        if (rightGroup[index]) {
          const e = rightGroup[index]
          const rightItem = { paymentYear2: e.paymentYear, paymentMonth2: e.paymentMonth, paymentBase2: e.paymentBase, companyPayment2: e.companyPayment, personalPayment2: e.personalPayment, paymentStatus2: e.paymentStatus }
          arr.push({ ...item, ...rightItem })
        }
        else {
          arr.push({ ...item })
        }
      })
      paymentData = [...arr]
      fillPaymentTable(paymentData)
    }
    // 获取要导出的HTML元素
    const element = document.getElementById('content')

    const pdf = new jsPDF()
    // 使用 html2pdf 将 HTML 元素导出为 PDF
    exportButton.addEventListener('click', () => {
      document.getElementById("exportButton").hidden = true
      window.document.title = `${info.name}社保`
      window.print()
      document.getElementById("exportButton").hidden = false
      window.document.title = `社保记录`
    })
  </script>
</body>

</html>